using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 微信推送通知控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class WeChatNotificationController : ControllerBase
    {
        private readonly IWeChatNotificationService _weChatNotificationService;
        private readonly ILogger<WeChatNotificationController> _logger;

        public WeChatNotificationController(
            IWeChatNotificationService weChatNotificationService,
            ILogger<WeChatNotificationController> logger)
        {
            _weChatNotificationService = weChatNotificationService;
            _logger = logger;
        }

        /// <summary>
        /// 手动发送退费申请提交成功通知
        /// </summary>
        /// <param name="request">通知请求</param>
        /// <returns>发送结果</returns>
        [HttpPost("send-refund-submitted")]
        public async Task<ActionResult> SendRefundSubmittedNotification([FromBody] SendNotificationRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { success = false, message = "患者ID不能为空" });
                }

                var result = await _weChatNotificationService.SendRefundSubmittedNotificationAsync(request.PatientId, request.RefundId);
                
                if (result.Success)
                {
                    return Ok(new { success = true, message = result.Message, xml = result.GeneratedXml });
                }
                else
                {
                    return BadRequest(new { success = false, message = result.Message, error = result.ErrorDetails });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"手动发送退费申请提交成功通知失败 - 患者ID: {request.PatientId}, 退费ID: {request.RefundId}");
                return StatusCode(500, new { success = false, message = "发送通知失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 手动发送退费审核通过通知
        /// </summary>
        /// <param name="request">通知请求</param>
        /// <returns>发送结果</returns>
        [HttpPost("send-refund-approved")]
        public async Task<ActionResult> SendRefundApprovedNotification([FromBody] SendNotificationRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { success = false, message = "患者ID不能为空" });
                }

                var result = await _weChatNotificationService.SendRefundApprovedNotificationAsync(request.PatientId, request.RefundId);
                
                if (result.Success)
                {
                    return Ok(new { success = true, message = result.Message, xml = result.GeneratedXml });
                }
                else
                {
                    return BadRequest(new { success = false, message = result.Message, error = result.ErrorDetails });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"手动发送退费审核通过通知失败 - 患者ID: {request.PatientId}, 退费ID: {request.RefundId}");
                return StatusCode(500, new { success = false, message = "发送通知失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 手动发送退费审核拒绝通知
        /// </summary>
        /// <param name="request">通知请求</param>
        /// <returns>发送结果</returns>
        [HttpPost("send-refund-rejected")]
        public async Task<ActionResult> SendRefundRejectedNotification([FromBody] SendRejectedNotificationRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { success = false, message = "患者ID不能为空" });
                }

                var result = await _weChatNotificationService.SendRefundRejectedNotificationAsync(request.PatientId, request.RefundId, request.Reason);
                
                if (result.Success)
                {
                    return Ok(new { success = true, message = result.Message, xml = result.GeneratedXml });
                }
                else
                {
                    return BadRequest(new { success = false, message = result.Message, error = result.ErrorDetails });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"手动发送退费审核拒绝通知失败 - 患者ID: {request.PatientId}, 退费ID: {request.RefundId}");
                return StatusCode(500, new { success = false, message = "发送通知失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成微信推送消息XML（测试用）
        /// </summary>
        /// <param name="request">微信消息请求</param>
        /// <returns>生成的XML</returns>
        [HttpPost("generate-xml")]
        public async Task<ActionResult> GenerateWeChatMessageXml([FromBody] WeChatMessageRequest request)
        {
            try
            {
                var xml = await _weChatNotificationService.GenerateWeChatMessageXmlAsync(request);
                return Ok(new { success = true, xml = xml });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成微信推送消息XML失败");
                return StatusCode(500, new { success = false, message = "生成XML失败", error = ex.Message });
            }
        }
    }

    /// <summary>
    /// 发送通知请求模型
    /// </summary>
    public class SendNotificationRequest
    {
        /// <summary>
        /// 患者ID
        /// </summary>
        public string PatientId { get; set; } = string.Empty;

        /// <summary>
        /// 退费申请ID
        /// </summary>
        public int RefundId { get; set; }
    }

    /// <summary>
    /// 发送拒绝通知请求模型
    /// </summary>
    public class SendRejectedNotificationRequest : SendNotificationRequest
    {
        /// <summary>
        /// 拒绝原因
        /// </summary>
        public string Reason { get; set; } = string.Empty;
    }
}